package com.franklin.ideaplugin.api.utils;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.franklin.ideaplugin.api.thread.MyCountDownLatch;

/**
 * @author Franklin
 * @since 2021/9/16 17:54
 */
public class DocumentUtils {

    /**
     * 同步写，防止画面撕裂，且内容不一致<br>
     * @author Franklin
     * @since 2021/9/16 18:04
     * @param project:
     * @param writeTask:
     * @return void
     */
    public static void writeSync(Project project, Runnable writeTask){
        MyCountDownLatch myCountDownLatch = new MyCountDownLatch(1);
        WriteCommandAction.runWriteCommandAction(project,() -> {
            writeTask.run();
            myCountDownLatch.countDown();
        });
        myCountDownLatch.await();
    }

    public static void writeSync(Runnable writeTask){
        MyCountDownLatch myCountDownLatch = new MyCountDownLatch(1);
        ApplicationManager.getApplication().runWriteAction(() -> {
            writeTask.run();
            myCountDownLatch.countDown();
        });
        myCountDownLatch.await();
    }
}
